import json

import requests

app_key = "682801"
app_sec = "1eb7ef009654c0ef398e71f0299cd80d"
weidia_auth_url = "https://oauth.open.weidian.com/token"
weidia_api_url = "https://api.vdian.com/api"
access_token = ''


def update_price(itemid, price):
    global access_token
    if access_token is '':
        payload = {'grant_type': 'client_credential',
                   'appkey': app_key,
                   'secret': app_sec}
        r = requests.get(weidia_auth_url, params=payload)
        access_token = r.json().get("result").get("access_token")
    param = {'itemid': itemid}
    public = {'method': "vdian.item.get",
              'access_token': access_token,
              'format': "json",
              'version': '1.0'}
    payload = {'param': json.dumps(param),
               'public': json.dumps(public)}
    r = requests.get(weidia_api_url, params=payload)
    skus = r.json().get("result").get("skus")
    mskus = []
    for sku in skus:
        msku = {'id': sku.get("id"), "price": price}
        mskus.append(msku)
    param = {'item_infos': [{'item_id': itemid, 'price': price, "skus": mskus}]}
    public = {'method': "vdian.item.prices.update",
              'access_token': access_token,
              'format': "json",
              'version': '1.1'}
    payload = {'param': json.dumps(param),
               'public': json.dumps(public)}
    r = requests.get(weidia_api_url, params=payload)
    print(r.json())
